Object.defineProperty(global, '__stack', {
    get: function () {
        var orig = Error.prepareStackTrace;
        Error.prepareStackTrace = function (_, stack) {
            return stack;
        };
        var err = new Error;
        Error.captureStackTrace(err, arguments.callee);
        var stack = err.stack;
        Error.prepareStackTrace = orig;
        return stack;
    }
});

Object.defineProperty(global, '__line', {
    get: function () {
        return __stack[1].getLineNumber();
    }
});

const log4js = require('log4js');
log4js.configure({
    appenders: {
        stdout: {
            type: 'stdout'
        }
    },
    categories: {
        default: {
            appenders: ['stdout'], level: 'debug'
        }
    }
})

const logger = log4js.getLogger(),
	CDP = require('chrome-remote-interface'),
	fs = require('fs')

logger.debug('[' + __filename + ':' + __line + ']', 'start')
CDP({
	port: 9222,
	target(targets) {
		for (var i = 0; i < targets.length; i++) {
			if (targets[i].url.indexOf('https://nexam.cmbc.com.cn/wis18/userpaper.viewuserhispaperqueslist.flow') == 0) {
				return targets[i]
			}
		}
	}
}).then(client => {
	const {
        Network,
        Page,
        DOM,
        Runtime,
        Emulation
    } = client
    Promise.all([Network.enable(), Page.enable(), DOM.enable()]).then(async () => {
		logger.debug('[' + __filename + ':' + __line + ']', 'connect')
		
		while (true) {
			var {result} = await Runtime.evaluate({expression: 'document.querySelector(".STYLE8").innerText'})
			var question = result.value

			var {result} = await Runtime.evaluate({expression: 'document.querySelector(".STYLE03").innerText'})
			question += result.value
			
			// if (question.indexOf('回答正确') == -1) {
				fs.writeFileSync('C:\\Users\\ye\\Desktop\\tmp.txt', question + '\n\n', {
					flag : 'a'
				})
			// }

			var {result} = await Runtime.evaluate({expression: 'document.querySelectorAll(".button_01[value=下一道]").length'})
			if (result.value == 0) {
				break
			}

			await Runtime.evaluate({expression: 'document.querySelector(".button_01[value=下一道]").click()'})

			await sleep(5)
		}

		process.exit(0)
    }).catch(err => {
        logger.error('[' + __filename + ':' + __line + ']', err)
    })
})

function sleep(second) {
	return new Promise(resolve => {
		setTimeout(() => {
			resolve()
		}, second * 1000)
	})
}